package role

import (
	"easy-sys/base/dao"
	"easy-sys/base/entity"
	"github.com/jinzhu/gorm"
)

func List(sysRole SysRole, page entity.EasyPage) entity.EasyPage {
	var roles []SysRole
	dao.Db.Where(sysRole).Limit(page.PageSize()).Offset(page.PageOffset()).Find(&roles)
	page.Records = roles
	var total int
	dao.Db.Model(&SysRole{}).Where(sysRole).Count(&total)
	page.Total = total
	return page
}

func SaveRoleAuth(sysRole SysRole) {
	// 先删除旧的权限
	dao.Db.Delete(SysRoleMenu{}, "role_id = ? ", sysRole.RoleId)
	for _, authId := range sysRole.Auths {
		sysRoleMenu := SysRoleMenu{}
		sysRoleMenu.MenuId = authId
		sysRoleMenu.RoleId = sysRole.RoleId
		dao.Db.Create(&sysRoleMenu)
	}
}

func InsertRoleUserByRole(sysRole SysRole) {
	if sysRole.UserIds != nil && len(sysRole.UserIds) > 0 {
		for _, userId := range sysRole.UserIds {
			sysRoleUser := SysRoleUser{}
			sysRoleUser.RoleId = sysRole.RoleId
			sysRoleUser.UserId = userId
			var sysRoleUsers []SysRoleUser
			dao.Db.Where(sysRoleUser).Find(&sysRoleUsers)
			if len(sysRoleUsers) == 0 {
				dao.Db.Create(&sysRoleUser)
			}
		}
	}
}

func DeleteRoleUserByRole(sysRole SysRole) {
	if len(sysRole.UserIds) > 0 {
		for _, userId := range sysRole.UserIds {
			sysRoleUser := SysRoleUser{}
			sysRoleUser.RoleId = sysRole.RoleId
			sysRoleUser.UserId = userId
			dao.Db.Where("role_id = ?", sysRole.RoleId).Delete(&sysRoleUser)
		}
	}
}

func Save(sysRole SysRole) int64 {
	var db *gorm.DB
	if sysRole.RoleId ==0 {
		db = dao.Db.Create(&sysRole)
	}else {
		db = dao.Db.Model(&sysRole).Where("role_id = ?", sysRole.RoleId).Update(&sysRole)
	}
	return db.RowsAffected
}

func Delete(sysRole SysRole) int64 {
	var db *gorm.DB
	if sysRole.RoleId != 0 {
		db = dao.Db.Where("role_id = ?", sysRole.RoleId).Delete(&sysRole)
	}
	return db.RowsAffected
}
